<template>
  <div class="user-dashboard">
    <!-- Header Section with User Info -->
    <el-card class="header-section" shadow="hover">
      <el-row :gutter="10">
        <!-- User Info Section (Left Side) -->
        <el-col :span="12">
          <div class="user-info">
            <!-- 上传按钮 -->
            <el-upload
              class="avatar-uploader"
              action="/user/upload-avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            ></el-upload>

            <!-- 头像展示部分，点击跳转 -->
            <div class="avatar-container" @click="goToUserInfoPage">
              <img
                v-if="user.pic_url"
                :src="user.pic_url"
                alt="User Avatar"
                class="avatar"
                @error="handleImageError"
              />
              <el-avatar v-else src="https://via.placeholder.com/50x50.png?text=头像"></el-avatar> 
            </div>

            <div class="user-details">
              <p class="mobile">{{ maskedMobile }}</p>
            </div>

            <div class="header-icons">
              <el-icon><ChatDotSquare /></el-icon>
              <el-icon><Setting /></el-icon>
            </div>
          </div>
        </el-col>

        <!-- Real Name Authentication Section -->
        <el-col :span="12">
          <div class="real-name-section">
            <p class="authentication-tip">
              请上传身份证的正面照片进行实名认证
            </p>
            <el-row :gutter="5">
              <el-col :span="12">
                <input type="file" accept="image/jpg/png" @change="fnUpload">
              </el-col>
              <el-col :span="12">
                <el-button type="primary" icon="el-icon-upload" @click="fnIdCard">实名认证</el-button>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="pet-section" shadow="hover">
      <div class="pet-info">
        <el-row align="middle" type="flex" justify="end" :gutter="40">
          <!-- 我的宠物标题 -->
          <el-col :span="6">
            <h3 class="pet-title" @click="togglePetDropdown">我的宠物</h3>
          </el-col>
          
          <!-- 宠物选择下拉框 -->
          <el-col :span="12">
            <el-select
              v-model="value"
              clearable
              placeholder="请选择宠物"
              style="width: 240px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>

          <!-- 添加按钮 -->
          <el-col :span="6" class="add-pet-button">
            <!-- <el-button type="primary" icon="el-icon-plus" @click="addPet" round>添加</el-button> -->
            <el-button type="primary" icon="el-icon-plus" @click="addPet">添加</el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>


    <!-- Tools and Services Section -->
    <el-card class="tools-section" shadow="hover">
      <el-row :gutter="20">
        <!-- 我的订单 -->
        <el-col :span="6" class="tool-item" @click="goOrder">
          <el-icon><Coin /></el-icon>
          <p>我的订单</p>
        </el-col>
        <el-col :span="6" class="tool-item" @click="goAppraise">
          <el-icon><Document /></el-icon>
          <p>我的评价</p>
        </el-col>
        <el-col :span="6" class="account-item">
          <p>我的收藏</p>
          <p>0</p>
        </el-col>
        <el-col :span="6" class="account-item">
          <p>浏览记录</p>
          <p>0</p>
        </el-col>
      </el-row>
    </el-card>
    <nav class="bottom-nav">
      <el-row justify="space-around" align="middle">
        <el-col :span="6" @click="goHome" :class="isActiveTab('home')">
          <el-button type="text">
            <el-icon><House /></el-icon>
            首页
          </el-button>
        </el-col>
        <el-col :span="6" @click="goPetShop" :class="isActiveTab('record')">
          <el-button type="text">
            <el-icon class="nav-icon"><Notebook /></el-icon>
            商品分类
          </el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="text" @click="goRecord">
            <el-icon class="nav-icon"><Reading /></el-icon>
            宠物信息
          </el-button>
        </el-col>
        <el-col :span="6" @click="goInformation" :class="isActiveTab('profile')">
          <el-button type="text">
            <el-icon><User /></el-icon>
            我的
          </el-button>
        </el-col>
      </el-row>
    </nav>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref, computed } from "vue"; // 确保引入 computed
import { get, post } from '@/utils/request';
import axios from "axios";

import { useRouter } from "vue-router";

import {
  House,
  Notebook,
  Coin,
  ShoppingCart,
  User,
  CreditCard,
  Document,
  Reading,
} from "@element-plus/icons-vue";

const router = useRouter();

const currentTab = ref("home");

const user = reactive({
  id: "",
  mobile: "",
  pic_url: "",
});
const pets = ref([]); // 初始化为空数组
const upFile = ref('')
const idCardRes = ref('')
const counter = ref('')
const value = ref('')
const options = [
  {
    value: 'Option1',
    label: 'Option1',
  },]
const maskedMobile = computed(() => {
  if (user.mobile && user.mobile.length === 11) {
    return user.mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
  }

  return user.mobile;
});

const handleImageError = (event) => {
  event.target.src = "https://via.placeholder.com/50x50.png?text=头像";
};

onMounted(async () => {
  try {
    const response = await axios.get("http://127.0.0.1:8000/user/info/", {
      params: { id: user.id },
    });

    if (response.data.code === 200 && response.data.data.length > 0) {
      const userData = response.data.data[0];

      user.id = userData.id;

      user.mobile = userData.mobile;

      user.pic_url = userData.pic_url
        ? `http://127.0.0.1:8000${userData.pic_url}`
        : "";
    }
  } catch (error) {
    console.error("Failed to fetch user info:", error);
  }
});

const handleAvatarSuccess = (response) => {
  user.pic_url = response.data.url;
};

const fnUpload = (event) => {
  // console.log(event);
  upFile.value = event.target.files[0];
  // console.log(upFile.value);
  
}

const fnIdCard = () => {
  let fd = new FormData();
  fd.append('file', upFile.value);
  post('http://127.0.0.1:8000/user/idcard/', fd).then((result) => {
    if(result.data.code == 200){
      alert('正在上传请稍后~');
      // 调用定时器
      counter.value = setInterval(timesIdCard, 1000, fd);   
    }
  }).catch((err) => {
    
  });
}

// 定时器
const timesIdCard = (file) => {  
  post('http://127.0.0.1:8000/user/idcardres/', file).then((result) => {
    if (result.data.code == 200) {
      idCardRes.value = result.data.res;   
      // console.log(idCardRes.value);         
      if(idCardRes.value){               
        clearInterval(counter.value);
        alert('认证成功');
      }else{                        
        clearInterval(counter.value);
        alert('认证失败');
      }
    }  
  }).catch((err) => {
              
  });
}


const onSubmit = () => {
  console.log('submit!')
}
const goToUserInfoPage = () => {
  router.push({ name: "info" });
};

const goHome = () => {
  currentTab.value = "home";

  router.push("/");
};

const goPetShop = () => router.push("/petshop");

const goOrder = () => {
  currentTab.value = "order";

  router.push("/order");
};
const goCart = () => {
  currentTab.value = "shopingcart";

  router.push("/shopingcart");
};
const goAppraise = () => {
  currentTab.value = "appraise";

  router.push("/appraise");
};

const goInformation = () => {
  currentTab.value = "profile";

  router.push("/information");
};
const goRecord = () => {
  currentTab.value = "record";

  router.push("/record");
};

const addPet = () => {
  currentTab.value = "add";

  router.push("/add");
};

const isActiveTab = (tabName) => {
  return currentTab.value === tabName ? "active-tab" : "";
};
</script >

<style scoped>
.user-dashboard {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #f0f8f5;
  padding: 20px;
}


.header-section, .pet-section, .tools-section {
  background-color: #ffffff;
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 20px; /* 增加内边距 */
  margin-bottom: 20px; /* 增加外边距 */
}


.user-info {
  display: flex;
  align-items: center;
  gap: 15px; /* 增加头像与用户信息之间的间距 */
}

.user-details p {
  margin: 0;
  font-weight: bold;
  color: #333;
}


.avatar-container {
  cursor: pointer;
  margin-left: 10px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.user-details p {
  margin-left: 10px;
  font-weight: bold;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.real-name-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pet-info {
  display: flex;
  align-items: center;
  gap: 15px;
}


.el-select {
  width: 100%; /* 让下拉框占满可用宽度 */
}


.add-pet-button {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.tools-section .tool-item {
  text-align: center;
  padding: 15px 0; /* 调整工具项内边距 */
  margin: 5px 0; /* 设置工具项的上下外边距 */
  border-radius: 10px;
  transition: transform 0.3s ease;
}


.tools-section .tool-item:hover {
  transform: scale(1.1);
}

.bottom-nav {
  padding: 15px 0; /* 增加顶部和底部内边距 */
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.bottom-nav .el-button {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #3498db;
  font-size: 14px; /* 调整字体大小 */
}


.nav-icon {
  font-size: 28px;
  color: #3498db;
  margin: 0 4px;
  transition: transform 0.3s ease, color 0.3s ease;
}

.nav-icon:hover {
  transform: scale(1.2);
  color: #2980b9;
}

.bottom-nav .el-button {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #3498db;
  transition: background-color 0.3s ease;
}

.bottom-nav .el-button:hover {
  background-color: #d9edf7;
}

@media (max-width: 768px) {
  .bottom-nav .el-button {
    padding: 5px;
  }

  .nav-icon {
    font-size: 24px;
  }
}
.tool-item:hover, .add-pet-button:hover, .bottom-nav .el-button:hover {
  transform: scale(1.05); /* 放大效果 */
  background-color: #f5fafd; /* 悬浮背景色 */
}

.header-section:hover, .pet-section:hover, .tools-section:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15); /* 增强悬停阴影 */
}

</style>